﻿using Common.MefHelp.Attributes;
using Common.Tools;
using System.Diagnostics;
using System.Text.Json;

namespace Common.Self.Computer
{
    /// <summary>
    /// windows资源实现类
    /// </summary>
    [CustomInjection("windows", typeof(IResource))]
    public class WindowResource : IResource
    {
        /// <summary>
        /// 定时器
        /// </summary>
        private readonly Timer _countTimer;
        /// <summary>
        /// Cpu计数器
        /// </summary>
        private readonly PerformanceCounter _cpuCounter;
        /// <summary>
        /// 内存计数器
        /// </summary>
        private readonly PerformanceCounter _ramCounter;

        /// <summary>
        /// cpu
        /// </summary>
        private float _cpu;
        /// <summary>
        /// 内存空闲
        /// </summary>
        private float _ramFree;
        /// <summary>
        /// 构造函数
        /// </summary>
        public WindowResource()
        {
#pragma warning disable CA1416 // 验证平台兼容性 
            _cpuCounter = new PerformanceCounter
            {
                CategoryName = "Processor",
                CounterName = "% Processor Time",
                InstanceName = "_Total"
            };
            _ramCounter = new PerformanceCounter("Memory", "Available MBytes");
#pragma warning restore CA1416 // 验证平台兼容性 
            Init().Wait();
            _countTimer = new Timer(CountHandler, null, 1000, Timeout.Infinite);
        }
        /// <summary>
        /// 定时计数
        /// </summary>
        /// <param name="state"></param>
        private void CountHandler(object? state)
        {
            try
            {
#pragma warning disable CA1416 // 验证平台兼容性
                _cpu = _cpuCounter.NextValue();
                _ramFree = _ramCounter.NextValue();
#pragma warning restore CA1416 // 验证平台兼容性
            }
            catch (Exception e)
            {
                LogHelper.Error(e);
            }
            finally
            {
                //一分钟查一次
                _countTimer.Change(60 * 1000, Timeout.Infinite);
            }
        }
        /// <summary>
        /// 获取Cpu资源
        /// </summary>
        /// <returns></returns>
        public Task<float> GetCpuAsync()
        {
            return Task.FromResult(_cpu);
        }
        /// <summary>
        /// 获取内存资源
        /// </summary>
        /// <returns></returns>
        public Task<float> GetAvailableMemeoryAsync()
        {
            return Task.FromResult(_ramFree);
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        public async Task Init()
        {
#pragma warning disable CA1416 // 验证平台兼容性
            _cpuCounter.NextValue();
            await Task.Delay(1000); // 等待一段时间以便 PerformanceCounter 更新值
            _cpu = _cpuCounter.NextValue();
            _ramFree = _ramCounter.NextValue();
#pragma warning restore CA1416 // 验证平台兼容性 
        }
    }
}
